package 剑指Offer._6170;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/10/9 8:57
 * 不用加减乘除做加法
 * 算法：位运算
 * 看成两个补码相加
 * 有四种情况
 *   1、x = 1, y = 1 ==> t = 1
 *   2、x = 1, y = 0 ==> t = t
 *   3、x = 0, y = 1 ==> t = t
 *   4、x = 0, y = 0 ==> t = 0
 * 其中 2、3 可视为同一种情况
 */
public class _65 {

    public int add(int a, int b) {
        int ans = 0, t = 0;
        for (int i = 0; i < 32; i++) {
            int x = (a >> i) & 1, y = (b >> i) & 1;
            if (x == 1 && y == 1) {
                ans |= (t << i);
                t = 1;
            } else if (x == 1 || y == 1) {
                ans |= (1 ^ t) << i;
            } else {
                ans |= (t << i);
                t = 0;
            }
        }
        return ans;
    }

}
